<?php
/**
 * JE FAQ Pro package
 * @author J-Extension <contact@jextn.com>
 * @link http://www.jextn.com
 * @copyright (C) 2010 - 2011 J-Extension
 * @license GNU/GPL, see LICENSE.php for full license.
**/

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

// Import Joomla! Plugin library file
jimport('joomla.plugin.plugin');
jimport('joomla.html.pagination');
JPlugin::loadLanguage( 'plg_content_jefaqpro', JPATH_ADMINISTRATOR );

/**
 * Class plgContentEcomportfolio
 * @author Daniel Gutierrez
 */
class plgContentjefaqpro extends JPlugin
{

	/**
	 * Constructor
	 * For php4 compatability
	 * @since 1.1
	 */
	function plgContentjefaqpro( &$subject, $params )
	{

		parent::__construct( $subject, $params );
	}

	/**
	 * Replace the testimonials and show testimonial contents and themes in article
	 */
	public function onPrepareContent( &$row, &$params, $page=0 )
	{

		global $database, $mainframe, $mosConfig_live_site, $_MAMBOTS;

		$portfolio = "";

		// simple performance check to determine whether bot should process further
		if ( JString::strpos( $row->text, '{faqpro' ) === false ) {
			return true;
		}

		// define the regular expression for the bot
		$regex = '/{faqpro\s*.*?}/i';

		// check whether plugin has been unpublished
		if ( !$this->params->get( 'enabled', 1 ) )	{
		        $row->text = preg_replace( $regex, '', $row->text );
		        return true;
		}

		// find all instances of plugin and put in $url_video
		preg_match_all( $regex, $row->text, $matches);

		// Number of plugins
		$count = count( $matches[0] );

		// Plugin only processes if there are any instances of the plugin in the text
		if ( $count ) {
			$row->text = preg_replace_callback( $regex, array($this, 'getPortfolio'), $row->text );
		}
	}

	function get_between ($text, $s1, $s2) {
		$mid_url 	= "";
		$pos_s 		= strpos($text,$s1);
		$pos_e 		= strpos($text,$s2);
		for ( $i=$pos_s+strlen($s1) ; (( $i<($pos_e)) && $i < strlen($text)) ; $i++ ) {
			$mid_url .= $text[$i];
		}
		return $mid_url;
	}

	/**
	 * Display the portfolio images
	 * @param array $matches A array with regex content.
	 */
	protected function getPortfolio(&$matches)
	{
		$faqPluginText 					= explode("|",$this->get_between($matches[0],'{','}'));
		global $database, $mainframe, $mosConfig_live_site, $_MAMBOTS;

		$context			= 'com_jefaqpro.s.id.list.';
		$sort 				= $this->params->get('sort');
		$sort_order			= 's.'.$sort;
		$filter_order		= $mainframe->getUserStateFromRequest( $context.'filter_order',		'filter_order',	$sort_order ,	'cmd' );

		$settings 		= $this->getSettings();

		if ($settings->cat_perpage != '0')
			$limit = $settings->cat_perpage;

		$limitstart 		= JRequest::getVar('jelimitstart', 0, '', 'int');
        $limitstart 		= ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);

        //Function getResponses

        $responses=$this->getResponses();

		// function for total count
		$total     			= $this->getTotal($filter_order,$faqPluginText);
		require_once(JPATH_SITE.DS."plugins".DS."content".DS."jefaqpro".DS."pagination.php");
		$pageNav   			= new JEPaginationFAQ( $total, $limitstart, $limit );
		$limit				= $pageNav->limit;
		$limitstart		    = $pageNav->limitstart;

		//get plugin parameter 'order'
		$order=$this->params->get('order');

		//$sorting = $this->faqproorder( $order, $sort );

		// function for get FAQs
		$rows     			= $this->getFaqpro($filter_order,$limitstart,$limit,$order,$faqPluginText);
		$themes = $this->getTheme();
		$limitfaqitems 				= 0;
		if(isset($faqPluginText[1]))
		if($faqPluginText[1]=='count'){
			if(isset($faqPluginText[2]))
			if($faqPluginText[2]){
				$limitfaqitems 		=(int)$faqPluginText[2];
			}
		}
		$pageNav->jelimitstart = $limitstart;
		$faqpros 		= $this->displayFaqpro($rows,$settings,$pageNav,$themes,$responses);

		return $faqpros;
	}
	protected function getTheme()
	{
		$db    = & JFactory::getDBO();
		$query = 'SELECT s.* FROM #__je_faq_themes AS s '	;
		$db->setQuery( $query);
		$themes = $db->loadObject();

		return $themes;
	}
	protected function getTotal($filter,$faqPluginText)
	{
		$where = array();

		$where[]    = 's.state = 1';   // while published

		//Check Category or FAQ from the {faqpro}
		if(isset($faqPluginText[1]))
		if($faqPluginText[1]=='c'){
			if(isset($faqPluginText[2]))
			if($faqPluginText[2]!= null){

				$aryText 					= explode(",",$faqPluginText[2]);
				foreach($aryText as $key => $value)
			        $aryText[$key]			= (int)$value;
				$faqPluginText[2]			= implode(",",$aryText);
				$where[]    				= 'catid IN ('.$faqPluginText[2].')';
			}
		}
		if(isset($faqPluginText[1]))
		if($faqPluginText[1]=='f'){
			if(isset($faqPluginText[2]))
			if($faqPluginText[2]!= null){
				$aryText 					= explode(",",$faqPluginText[2]);
				foreach($aryText as $key => $value)
			        $aryText[$key] 			= (int)$value;
				$faqPluginText[2] 			= implode(",",$aryText);
				$where[]    				= 'id IN ('.$faqPluginText[2].')';
			}
		}
		$limitfaqitems 						= 0;
		if(isset($faqPluginText[1]))
		if($faqPluginText[1]=='count'){
			if(isset($faqPluginText[2]))
			if($faqPluginText[2]){
				$limitfaqitems 				= (int)$faqPluginText[2];
				if(isset($faqPluginText[3]))
				if($faqPluginText[3]=='c'){
					if(isset($faqPluginText[4]))
					if($faqPluginText[4]!= null){
						$aryText 			= explode(",",$faqPluginText[4]);
						foreach($aryText as $key => $value)
					        $aryText[$key] 	= (int)$value;
						$faqPluginText[4] 	= implode(",",$aryText);
						$where[]    		= 'id IN ('.$faqPluginText[4].')';
					}
				}
			}
		}

		$where		= count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '';

		// get the total number of records
		$db    = & JFactory::getDBO();
		$query = 'SELECT count(*) FROM #__je_faq AS s '
			. $where
			;

		if($limitfaqitems)
			$query .= ' limit '.$limitfaqitems;
		$db->setQuery( $query );
		if (!$db->query()) {
			echo $db->getErrorMsg();
		}

		$total = $db->loadResult();

		return $total;
	}

	protected function getSettings()
	{
		$db    = & JFactory::getDBO();
		$query = 'SELECT s.* FROM #__je_faq_settings AS s '	;
		$db->setQuery( $query);
		$settings = $db->loadObject();

		return $settings;
	}

	protected function getResponses()
	{
		$db    = & JFactory::getDBO();
		$query = 'SELECT s.* FROM #__je_faq_responses AS s '	;
		$db->setQuery( $query);
		$responses = $db->loadObject();

		return $responses;
	}
	protected function getFaqpro($filter_order,$limitstart,$limit,$order,$faqPluginText)
	{

		$where = array();

		$where[]    = 's.state = 1';   // while published

		//Check Category or FAQ from the {faqpro}
		if(isset($faqPluginText[1]))
		if($faqPluginText[1]=='c'){
			if(isset($faqPluginText[2]))
			if($faqPluginText[2]!= null){

				$aryText 					= explode(",",$faqPluginText[2]);
				foreach($aryText as $key => $value)
			        $aryText[$key]			= (int)$value;
				$faqPluginText[2]			= implode(",",$aryText);
				$where[]    				= 'catid IN ('.$faqPluginText[2].')';
			}
		}
		if(isset($faqPluginText[1]))
		if($faqPluginText[1]=='f'){
			if(isset($faqPluginText[2]))
			if($faqPluginText[2]!= null){
				$aryText 					= explode(",",$faqPluginText[2]);
				foreach($aryText as $key => $value)
			        $aryText[$key] 			= (int)$value;
				$faqPluginText[2] 			= implode(",",$aryText);
				$where[]    				= 'id IN ('.$faqPluginText[2].')';
			}
		}
		$limitfaqitems 						= 0;
		if(isset($faqPluginText[1]))
		if($faqPluginText[1]=='count'){
			if(isset($faqPluginText[2]))
			if($faqPluginText[2]){
				$limitfaqitems 				= (int)$faqPluginText[2];
				if(isset($faqPluginText[3]))
				if($faqPluginText[3]=='c'){
					if(isset($faqPluginText[4]))
					if($faqPluginText[4]!= null){
						$aryText 			= explode(",",$faqPluginText[4]);
						foreach($aryText as $key => $value)
					        $aryText[$key] 	= (int)$value;
						$faqPluginText[4] 	= implode(",",$aryText);
						$where[]    		= 'id IN ('.$faqPluginText[4].')';
					}
				}
			}
		}

		$where		= count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '';
		$orderby	= ' ORDER BY '. $filter_order.' '.$order;

		$db    = & JFactory::getDBO();
		$query = 'SELECT s.* FROM #__je_faq AS s '
			. $where
			. $orderby
			;
		if($limitfaqitems)
			$db->setQuery($query,0, $limitfaqitems);
		else
			$db->setQuery( $query, $limitstart, $limit );
		$rows = $db->loadObjectList();

		return $rows;
	}

	protected function faqproorder($order,$sort)
	{

			$db    	  	  = & JFactory::getDBO();
			$orderby  	  = ' ORDER BY '.$sort.' '.$order;
			$query	  	  = 'SELECT * FROM #__je_faq WHERE state=1'.$orderby ;
			$db->setQuery( $query);
			$faqpros = $db->loadObjectList();

			if (count($faqpros)<1) {
				echo JText :: _('MOD_MES');
			}
			return $faqpros;
	}


	function getResponsecount( $id, $catid )
	{
		$db    	= & JFactory::getDBO();

		$query 	= 'SELECT sum(response_no) as response_no , sum(response_yes) as response_yes FROM #__je_faq_responses where faqid="'.$id.'" AND catid="'.$catid.'"';
		$db->setQuery( $query );

		if (!$db->query())	{
			echo $db->getErrorMsg();
		}

		$count  	= $db->loadObject();

		return $count;
	}

	function getResponsedet( $id, $catid )
	{
		$userid		='';
		$user 		= & JFactory::getUser();

		if ( $user->id > 0 ) {
			$userid		=  ' AND userid='.$user->id;
		}

		$query 	= 'SELECT * FROM #__je_faq_responses where faqid="'.$id.'" AND catid="'.$catid.'"'.$userid;

		$db    	= & JFactory::getDBO();
		$db->setQuery( $query );

		if (!$db->query())	{
			echo $db->getErrorMsg();
		}

		$res  	= $db->loadObject();

		return $res;
	}
//******************************* displayFaqpro *********************************************************

	protected function displayFaqpro($rows,$settings,$pageNav,$themes,$responses)
	{
		global $database, $mainframe, $mosConfig_live_site, $_MAMBOTS;


		$path 		= JURI::root();
		$doc        = & JFactory::getDocument();

		$js=JURI::root().'components/com_jefaqpro/assets/js/utilities.js';
		$js1=JURI::root().'components/com_jefaqpro/assets/js/accordionview.js';
		$js2=JURI::root().'components/com_jefaqpro/assets/js/iepngfix_tilebg.js';
		$css1=JURI::root().'components/com_jefaqpro/assets/css/accordionview.css';


		$css   	    = JURI::root().'components/com_jefaqpro/assets/css/style.css';

		JHTML::_('behavior.modal');

		$doc->addStyleSheet($css1);
		$doc->addStyleSheet($css);
		$doc->addScript($js);
		$doc->addScript($js1);
		$doc->addScript($js2);


		$uri 	= & JFactory::getURI();
		$user=& JFactory::getUser();

		$action = $uri->toString();

		$faqpro ='';

		$faqpro.= "<form action=\"$action\" method=\"post\" name=\"adminForm\">";
		$faqpro.= "<script type=\"text/javascript\" src=\"/joomla/joomla_new/media/system/js/mootools.js\"></script>";
  		$faqpro.= "<script type=\"text/javascript\">";
		$faqpro.= "window.addEvent('domready', function(){ var JTooltips = new Tips($$('.hasTip'), { maxTitleChars: 50, fixed: false}); });";
  		$faqpro.="</script>";


		$tempid	 	 =$settings->themes ;
		$template 	 = 'mymenu'.$tempid ;

		$faqpro.= "<form action=\"$action\" method=\"post\" name=\"adminForm\">";
		$faqpro.= "<div id=\"contentarea\" style=\"text-align : justify;\">";
		if ( count($rows) > 0 )
		{
			$faqpro.= "<div class=\"yui-skin-sam\">";
			$faqpro.= 	"<div id=\"wrapper1\">";
			$faqpro.= 		"<ul id=\"$template\">";

			$w = 1;
			$k=0;
			for ($i=0, $n=count( $rows ); $i < $n; $i++)
			{
				$row = &$rows[$i];
				$res			= $this->getResponsedet( $row->id,$row->catid );
				$count			= $this->getResponsecount( $row->id,$row->catid );

//**************************



					if ( $count->response_yes == '' )
							$count->response_yes = 0;
						if ( $count->response_no == '' )
							$count->response_no = 0;

							if($res==null)
							{
								$res->faqid=0;
								$res->userid=0;
							}

						if ( $settings->allow_reg == '1' ) {

								if ( $user->id > 0 ) {

									if ( $user->id == $res->userid && $row->id == $res->faqid && ( $count->response_yes > 0 || $count->response_no > 0) )	{

										$title		 = JText::_('JE_FAQ_ALREADY');
										$onclick_yes = "onclick=\"getResponse('$i', '1', '$row->id', '$row->catid','2');";
										$onclick_no  = "onclick=\"getResponse('$i', '2', '$row->id', '$row->catid','2');";


									} else {

										$title		 = JText::_('JE_FAQ_RESPONSE');
										$onclick_yes = "onclick=\"getResponse('$i', '1', '$row->id', '$row->catid','0');";
										$onclick_no  = "onclick=\"getResponse('$i', '2', '$row->id', '$row->catid','0');";

									}

								} else {

									$title = JText::_('JE_FAQ_LOGIN');
									$onclick_yes = "onclick=\"getResponse('$i', '1', '$row->id', '$row->catid','1');";
									$onclick_no  = "onclick=\"getResponse('$i', '2', '$row->id', '$row->catid','1');";

								}

						}  else {

							if ( $row->remote_ip == $res->remote_ip && $row->id == $res->faqid && ( $count->response_yes > 0 || $count->response_no > 0) )	{

								$onclick_yes = "onclick=\"getResponse('$i', '1', '$row->id', '$row->catid','2');";
								$onclick_no  = "onclick=\"getResponse('$i', '2', '$row->id', '$row->catid','2');";
								$title		 = JText::_('JE_FAQ_ALREADY');

							} else	{
								$title		 = JText::_('JE_FAQ_RESPONSE');
								$onclick_yes = "onclick=\"getResponse('$i', '1', '$row->id', '$row->catid','0');";
								$onclick_no  = "onclick=\"getResponse('$i', '2', '$row->id', '$row->catid','0');";
							}

						}

//**************************

				$faqpro.= "<li>";
				$faqpro.= 	"<p>".$row->questions."</p>";
				$faqpro.= 	"<div>";
				$faqpro.= 		"<div class=\"padded clearfix\">";
				if ($settings->show_author == '1' || $settings->show_date == '1')
				{
					$faqpro.= 		"<div id=\"je-posted\" style=\"padding : 5px; text-align : right; font-style : italic;\">";
					if ($settings->show_date == '1')
					{
						$faqpro.= 		"<span id=\"je-posteddate\">";

						$date 	 = new JDate( $row->posted_date );
						$posted  = $date->toFormat( $settings->date_format );

						$faqpro.=$posted;
						$faqpro.= 		"</span>";
					}
					if ($settings->show_author == '1')
					{
						$faqpro.= 		"<span id=\"je-author\">&nbsp;&nbsp;".$row->posted_by."</span>";
					}
					$faqpro.= 		"</div>";
				}

				// Diplay answers here..

				$faqpro.=$row->answers;
				if ($settings->show_response == '1')
				{

					$faqpro.= 		"<div style=\"padding : 5px 0px 5px 0px; \">";
					$faqpro.= 			"<ul id=\"je-response-ul\">";

					$faqpro.= 				"<li id=\"je-response\" > <span id=\"je-userlogin$i\"></span></li>";
					$faqpro.= 				"<li id=\"je-response\" > <span class=\"editlinktip hasTip\" title=\"".JText::_( 'JE_RESPONSE' )." :: ".JText::_( 'JE_LIKE' ) ."\"> <span id=\"je-responsetop$i\">".$count->response_yes."</span> <a id=\"je-atagtop$i\" href=\"javascript:void(0);\" $onclick_yes \"title=\"$title\" > <span id=\"je-top\"> &nbsp; </span> </a> </span> </li>";
					$faqpro.= 				"<li id=\"je-response\" > <span class=\"editlinktip hasTip\" title=\"". JText::_( 'JE_RESPONSE' )." :: ".JText::_( 'JE_DISLIKE' ) ."\"> <span id=\"je-responsebot$i\">".$count->response_no."</span> <a id=\"je-atagbot$i\" href=\"javascript:void(0);\" $onclick_no \"title=\"$title\" > <span id=\"je-bot\"> &nbsp; </span> </a> </span> </li>";
					$faqpro.= 			"</ul>";
					$faqpro.= 		"</div>";
				}
				if ($settings->show_hits == '1')
				{
					$faqpro.= 		"<div id=\"je-hits$w\" style=\"text-align : right; padding : 2px; font-style : italic;\" > ". JText::_('JE_FAQ_HITS') ."&nbsp;".$row->hits." </div>";
				}
				$faqpro.= 			"<input type=\"hidden\" name=\"ques_id$w\" id=\"ques_id$w\" value=\"$row->id\">";
				$faqpro.= 		"</div>";
				$faqpro.= 	"</div>";
				$faqpro.= "</li>";
				$w++;
				$k = 1 - $k;
			}
			$faqpro.= "</ul>";

			$faqpro.= "<input type=\"hidden\" name=\"path\" id=\"path\" value=\"".JURI::root()."\" />";
			$faqpro.= "<input type=\"hidden\" name=\"user_login\" id=\"user_login\" value=\"".JText::_('JE_FAQ_LOGIN')."\" />";
			$faqpro.= "<input type=\"hidden\" name=\"je_already_added\" id=\"je_already_added\" value=\"". JText::_('JE_FAQ_ALREADY') ."\" />";
			$faqpro.= "</div>";
			$faqpro.= "<script type=\"text/javascript\" src=".JURI::root().'components/com_jefaqpro/assets/js/accordionview.js'."></script>";
			$faqpro.= "<script type=\"text/javascript\">";
			$faqpro.= "var menu1 = new YAHOO.widget.AccordionView('$template', {collapsible: true, width: '100%', margin : '0', animationSpeed: '0.3', animate: true, effect: YAHOO.util.Easing.easeBothStrong})";
			$faqpro.="</script>";
			$faqpro.= "</div>";
		}
		else
		{
			$faqpro.="<div id=\"je-nofaqs\" style=\"text-align : center;\">".JText::_("JE_FAQS")."</div>";
		}
		$faqpro.="</div>";

		//<!-- New Button -->
		$user 	  = & JFactory::getUser();
		$itemid   = &JRequest::getVar('Itemid');
		$form	  = JRoute::_('index.php?option=com_jefaqpro&view=faq&layout=form&Itemid='.$itemid);
		if ( $settings->show_reguser == '1' ) {
			if ( $settings->show_form == '1' && $user->get('id') >0 ) {
				$faqpro.='<div id="je-newbutton">';
					$faqpro.='<div style="text-align : right">';
						$faqpro.='<a id="je-addbutton" href="'.$form.'" title="'.JText::_('JE_ADDNEW').'" > <strong> '.JText::_('JE_ADDNEW').'</strong> </a>';
					$faqpro.='</div>';
				$faqpro.='</div>';
			}
		} else {

			if ( $settings->show_form == '1' ) {
				$faqpro.='<div id="je-newbutton">';
					$faqpro.='<div style="text-align : right">';
						$faqpro.='<a id="je-addbutton" href="'.$form.'" title="'.JText::_('JE_ADDNEW').'" > <strong> '.JText::_('JE_ADDNEW').'</strong> </a>';
					$faqpro.='</div>';
				$faqpro.='</div>';
			}
		}
		//<!-- Ended New button -->

		//<!-- Pagination code start -->
				$faqpro .= "<div id=\"je-pagination\">";
				$faqpro .=	 	$pageNav->getListFooter();
				$faqpro .=	 "<input type=\"hidden\" name=\"jelimitstart\" value=\"$pageNav->jelimitstart\">";
				$faqpro .= "</div>";
		//<!-- Pagination code End -->

		$faqpro.= "</form>";

		return $faqpro;
	}

//*************************************** displayFaqpro End*********************************************







	protected function checkNum($num)
	{
	  return ($num%2) ? true : false;
	}
}